import { useMemo, useEffect, useState, RefObject} from 'react';

type Point = { x: number; y: number };

export const useSwipe = (element: RefObject<HTMLElement>) => {
  const [start, setStart] = useState<Point | null>(null);
  const [end, setEnd] = useState<Point | null>(null);
  const [swiping, setSwiping] = useState(false);
  const distance = useMemo(() => {
    if (!start || !end) return null;
    return {
      x: end.x - start.x,
      y: end.y - start.y,
    };
  }, [start, end]);

  const direction = useMemo(() => {
    if (!distance) return null;
    return Math.abs(distance.x) > Math.abs(distance.y)
      ? (distance.x > 0 ? 'right' : 'left')
      : (distance.y > 0 ? 'down' : 'up');
  }, [distance]);
  useEffect(() => {
    const onStart = (e: TouchEvent) => {
      e.preventDefault();
      setSwiping(true);
      setEnd({ x: e.touches[0].clientX, y: e.touches[0].clientY });
      setStart({ x: e.touches[0].clientX, y: e.touches[0].clientY });
    };

    const onMove = (e: TouchEvent) => {
      setEnd({ x: e.touches[0].clientX, y: e.touches[0].clientY });
    };

    const onEnd = () => {
      setSwiping(false);
    };
    if (!element.current) return
    element.current.addEventListener('touchstart', onStart);
    element.current.addEventListener('touchmove', onMove);
    element.current.addEventListener('touchend', onEnd);
    return () => {
      if (!element.current) return
      element.current.removeEventListener('touchstart', onStart);
      element.current.removeEventListener('touchmove', onMove);
      element.current.removeEventListener('touchend', onEnd);
    };
  }, [element]);

  return {
    swiping,
    distance,
    direction,
  };
};
